import router from '@system.router';
import prompt from '@system.prompt';
import featureAbility from '@ohos.ability.featureAbility';
import socket from '@ohos.net.socket';
import wifi from '@ohos.wifi';
export default {
    data: {
        title: "等待新的消息...",
        tcp: socket.constructTCPSocketInstance(),
        localip:'none',
        remoteip:'none',
        msg:"A NEW WORLD",
        udp:socket.constructUDPSocketInstance(),
        showconfig:0,
        TAG:"YZJ",
    },
    onInit() {this.grantPermission();
      this.getIpAddress();
      this.creatScoket();

      this.title="暂无新消息"
    },
    sendMsg(){

    },
    grantPermission() {
        console.info('Calc[IndexPage] grantPermission')
        let context = featureAbility.getContext()
        context.requestPermissionsFromUser(['ohos.permission.CAMERA', "ohos.permission.WRITE_MEDIA","ohos.permission.READ_MEDIA"], 666, function (result) {
            //            console.info(`Calc[IndexPage] grantPermission,requestPermissionsFromUser,result.requestCode=${result.requestCode}`)
        })
    },
    showdialog(){
      this.$element("dialog").show();
    },
    closedialog(){
      this.$element("diaglog").close();
    },
   async  creatScoket() {
        var that = this;
        this.udp.bind({address: this.localip, port: 10006, family: 1}, err => {
            if (err) {
                console.info(this.TAG+'bind fail');
                this.title='bind fail'
                return;
            }
            this.title='bind success';
            console.info(this.TAG+'bind success');
        })
       this.udp.on('message', value => {
           let buffer = value.message;
           let dataView = new DataView(buffer);
           let str = "";
           for (let i = 0;i < dataView.byteLength; ++i) {
               str += String.fromCharCode(dataView.getUint8(i))
           }
          if(parseInt(str)==0){
              var options= {
                  "quality":"normal",
                  "success":this.onSuccess(),

                  "fail":this.onFailed(),

                  "complete":this.onCompleted()

              }
              that.$element("c").takePhoto(options);
          }
           else{
//               router.push({
//                   uri:"pages/home/home"
//               })
//               this.showdialog();
           }
           //多加一步就好了  unicode解码
           that.title = str;
           console.info(this.TAG+str);


        });
    },
    onFailed:async function(){
        prompt.showToast({
            message: "拍摄失败"
        });
    },

    onSuccess:async function(e){
        console.info(this.TAG+JSON.stringify(e))
        prompt.showToast({
            message: "拍摄成功"
        });
    },
    onCompleted:async function(){
        prompt.showToast({
            message: "拍摄完成"
        });
    },
    cameraError(){
        prompt.showToast({
            message: "授权失败！"
        });
    },
    takepic(){

        var options= {
            "quality":"normal",
            "success":this.onSuccess(),

            "fail":this.onFailed(),

            "complete":this.onCompleted()

        }
        this.$element("c").takePhoto(options
        );
    },

    sendMessage: async function(){
        let promise = this.udp.send({
            data:this.msg,
            address: {
                address:this.remoteip,
                port:10006,
                family:1
            }
        });
        promise.then(() => {
            this.title='send success';
            console.info(this.TAG+'send success');
        }).catch(err => {
            this.title='send fail'
            console.info(this.TAG+'send fail');
        });
    },
    newlocalip(e){
       this.localip = e.value;
        this.title = e.value;
    },
    newremoteip(e){
        this.remoteip = e.value;
    },
    newMessage(e){
         this.msg=e.value;
        this.title=e.value;
    },
    encodeUtf8(text) {
        const code = encodeURIComponent(text);
        const bytes = [];
        for (var i = 0; i < code.length; i++) {
            const c = code.charAt(i);
            if (c === '%') {
                const hex = code.charAt(i + 1) + code.charAt(i + 2);
                const hexVal = parseInt(hex, 16);
                bytes.push(hexVal);
                i += 2;
            } else bytes.push(c.charCodeAt(0));
        }
        return bytes;
    },
    decodeUtf8(bytes) {
        var encoded = "";
        for (var i = 0; i < bytes.length; i++) {
            encoded += '%' + bytes[i].toString(16);
        }
        return decodeURIComponent(encoded);
    },
    unicodeTostr(str){
					var res = []; //存放结果
					var tmp = str.split('\\u');//根据 \u 分割
					var len = tmp.length; //长度
					for(var i=0; i<len; i++){
						if(tmp[i]){
                            //解析unicode
							res.push(String.fromCharCode(parseInt(tmp[i], 16)));//16 转 10
						}
					}
					return res.join('');
				},

    getIpAddress(){
       let ip=wifi.getIpInfo().ipAddress;
       this.localip = (ip >> 24 & 0xFF)+"."+ ((ip >> 16) & 0xFF)+"."+((ip >> 8) & 0xFF)+"."+(ip & 0xFF);
        console.info(this.TAG+this.localip)
    },


}



